import json
import os
import re
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
import random

from .models import User
from .check_authority import MysqlQuery
from .utils import MysqlFind

from django.core.serializers import serialize
from django.views import View
from rest_framework.response import Response
from rest_framework.views import APIView
from mydjango import settings

from .utils import get_uid, redis, chack_jwt,redis1
from mydjango import settings

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT

# 导入客服机器人
from .robotservice import qingyunke, xiaobing, tencent, tuling
from .robotservice import customrobot

# websocket接口
# 客户端列表
clients = {}
# is_send = False
# 推送提示消息websocket
@accept_websocket
def websocketlink(request):
    global is_send
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        ip = request.META.get('HTTP_X_FORWARDED_FOR')
    else:
        ip = request.META.get('REMOTE_ADDR')

    if redis1.sdiff('on_line_num',):
        redis1.sadd("on_line_num", ip)
    else:
        redis1.sadd("on_line_num", ip)
        redis.expire("on_line_num", 60*30)

    if request.is_websocket():
        userid = str(uuid.uuid1())

        while 1:
            # 获取Vue发送的token，进行解析获取出uid
            message = request.websocket.wait()
            if not message:
                break

            else:

                token = str(message.decode())[4:]
                uid = chack_jwt(token).get("uid")
                res = len(redis.hgetall(uid))
                if res > 0:
                    is_send = True
                    request.websocket.send(str(res).encode("utf-8"))
                # 把uid和websocket存到公共变量字典中
                clients[uid] = request.websocket

# 消息接口
class ShowMessage(APIView):

    def get(self, request):
        '''
        根据uid获取对应的消息
        '''
        data_list = []
        uid = get_uid(request)
        res = redis.hgetall(uid)
        for key, value in res.items():
            req_dict = {}
            req_dict["task_id"] = key.decode()
            req_dict["key"] = key.decode()
            req_dict["message"] = value.decode()
            data_list.append(req_dict)


        return Response({"code": 200, "data": data_list})

    def delete(self, request):
        '''
        消息已读
        '''
        task_id = request.data.get("task_id")
        uid = get_uid(request)
        try:
            redis.hdel(str(uid), str(task_id))
        except Exception as e:
            print(e)
            return Response({"code": 200, "data": "已读失败", "log": "将审批消息%s读取失败"%task_id})
        return Response({"code":200, "data": "已读成功", "log": "将审批消息%s读取成功"%task_id})


# 客服消息
# 消息客户端列表
msg_clients = {}

# 消息聊天websocket
@accept_websocket
def messagewebsocket(request):

    if request.is_websocket():

        while 1:
            # 获取Vue发送的token，进行解析获取出uid
            message = request.websocket.wait()

            if not message:

                break
            else:
                token = str(message.decode())[4:]
                uid = chack_jwt(token).get("uid")


                # 把uid和websocket存到公共变量字典中
                msg_clients[str(uid)] = request.websocket


class SendMessage(APIView):
    # # 推送消息
    def post(self,request):
        # 根据id获取用户名称
        token = request.META.get("HTTP_AUTHORIZATION")
        token = str(token)[4:]
        send_uid = chack_jwt(token).get("uid")
        # 获取消息
        msg = request.data.get("msg")
        receipt_id = request.data.get("id")
        sql = 'select id,username, nickname,photo from user where id=' + str(send_uid)
        result = MysqlFind(sql).sql_select()
        if not result:
            return HttpResponse({"code": 999, "message": "用户不存在"})
        result = result[0]
        # 如果10秒钟发送了3次或以上就超时
        num = redis1.get(str(send_uid))
        if num:
            # 如果没有的话就存一个，设置超时间为10秒
            redis1.incr(send_uid)
            if int(num) >= 3:
                return HttpResponse({"code": 999, "msg": "发送频繁"})
        else:
            # 把redis的uid的值每次加一
            redis1.set(send_uid, 1, ex=10)
        # 如果id为0说明是给客服发送信息，将用户发的信息和客服发的都存到数据库种，然后返回客服回复的信息
        if receipt_id == 0:
            res = tencent(msg)  # 腾讯的机器人
            # res = qingyunke(msg)  # 青云客的机器人
            # res = xiaobing(msg)  # 微软的机器人
            # res = tuling(msg)  # 图灵机器人
            # res = customrobot(msg)  # 自定义机器人
        #
            # print("机器人回复：",res)
            key = "%s:%s" % (send_uid, receipt_id)
            value = {"type": "msg", "msg": msg, "photo": result.get("photo"), "id": send_uid,
                            "username": result.get("nickname")}
            res_value = {"type": "msg", "msg": res, "photo": 'wallhaven-39xv99.jpg', "id": 0,
                            "username": result.get("nickname")}
            redis_value = json.dumps(value, ensure_ascii=False)
            res_redis_value = json.dumps(res_value, ensure_ascii=False)

            if redis.lrange(key, 0, 0):

                redis1.lpush(key, redis_value)
                redis1.lpush(key, res_redis_value)
            else:
                redis1.lpush(key, redis_value)
                redis1.lpush(key, res_redis_value)
                redis1.expire(key, 60 * 60 * 24)
            return HttpResponse({"code":200, "message": "ok", "log": ""})



        if int(send_uid) >= int(receipt_id):
            key = "%s:%s" % (send_uid, receipt_id)
        else:
            key = "%s:%s" % (receipt_id, send_uid)
        value = {"type": "msg", "msg": msg, "photo": result.get("photo"), "id": send_uid,
                            "username": result.get("nickname")}
        redis_value = json.dumps(value, ensure_ascii=False)
        if redis.lrange(key, 0, 0):

            redis1.lpush(key, redis_value)
        else:
            redis1.lpush(key, redis_value)
            redis1.expire(key, 60*60*24)

        if str(receipt_id) in list(msg_clients.keys()):
            msg_clients.get(str(receipt_id)).send(redis_value.encode("utf-8"))
            # msg_clients.get(str(send_uid)).send(redis_value.encode("utf-8"))
        else:
            return Response({"code": 200, "msg": "用户不在线", "log": "向用户%s发送了%s" % (receipt_id, msg)})

        # 存入redis,设置超时时间为10秒
        redis1.expire(key,100)

        return HttpResponse({"code":200, "message": "ok", "log": "向用户%s发送了%s" % (receipt_id, msg)})


class OnlineUser(APIView):
    def get(self, request):
        id_list = list(msg_clients.keys())
        user_obj = User.objects.filter(id__in=id_list)
        data = [{"uid": i.id, "username": i.username, "nickname": i.nickname} for i in user_obj]
        people_num = len(redis1.sdiff('on_line_num'))
        print("人数", people_num)

        return Response({"code":200, 'data':data,"people_num": people_num})


class MsgImg(View):

    # 上传方法
    def post(self, request):
        send_uid = request.GET.get("uid")
        receipt_id = request.GET.get("id")
        #接收参数112
        if not all([send_uid, receipt_id]):
            return Response({"code": 999, "data":"参数不齐"})

        sql = 'select id,username, nickname,photo from user where id=' + str(send_uid)
        result = MysqlFind(sql).sql_select()[0]

        img = request.FILES.get('file')

        # 建立文件流
        with open(os.path.join(UPLOAD_ROOT, '', img.name), 'wb') as f:
            for chunk in img.chunks():
                # print(chunk)
                f.write(chunk)
        if int(send_uid) >= int(receipt_id):
            key = "%s:%s" % (send_uid, receipt_id)
        else:
            key = "%s:%s" % (receipt_id, send_uid)
        print(result)
        if redis1.lrange(key,0,0):
            value = json.dumps({"type":"file", "msg":img.name,"photo": result.get("photo"),"id":send_uid, "username": result.get("nickname")})
            redis1.lpush(key, value)
        else:
            value = json.dumps({"type":"file", "msg": img.name, "photo": result.get("photo"), "id": send_uid,
                     "username": result.get("nickname")}, ensure_ascii=False)
            redis1.lpush(key, value)
            redis1.expire(key, 60*60*24)
        return HttpResponse(json.dumps({"filename": img.name},ensure_ascii=False), content_type='application/json')


class ShowMsgRecord(APIView):

    def post(self, request):
        # send_id = request
        send_uid = request.data.get("send_id")
        receipt_id = request.data.get("receipt_id")
        if int(send_uid) >= int(receipt_id):
            key = '%s:%s' % (send_uid,receipt_id)
        else:
            key = '%s:%s' % (receipt_id, send_uid)

        print(key)
        data = redis1.lrange(key, 0, -1)
        for i in range(len(data)-1,-1,-1):
            data[i] = json.loads(data[i])
            if data[i].get("type") == "file":
                suffix = data[i].get("msg").split('.')[-1]
                if suffix == 'mp3':
                    data[i]['type'] = 'mp3'
                else:
                    data[i]['type'] = 'img'
        print(data)

        return Response({"code": 200, "data": data})








